<template>
  <div class="todo">
    <input type="checkbox" :checked="todo.isChecked" @change="changeId(todo.id)">
    <span v-show="!todo.isEdit">{{todo.name}}</span>
    <input v-show="todo.isEdit" type="text" :value="todo.name" @blur="saveEdit(todo,$event)" ref="inputName">
    <span @click="editThisTodo(todo)" class="editBtn">编辑</span>
    <span @click="deleteThisTodo(todo.id)" class="delBtn">删除任务</span>
  </div>
</template>

<script>
import pubsub from 'pubsub-js'

export default {
  name: 'MyTodo',
  props: ['todo'],
  methods: {
    changeId (id) {
      // this.$bus.$emit('changeStatusRecieveId', id)
      pubsub.publish('changeStatusRecieveId', id)
    },
    deleteThisTodo (id) {
      // this.$bus.$emit('deleteTodo', id)
      pubsub.publish('deleteTodo', id)
    },
    editThisTodo (todo) {
      if (todo.hasOwnProperty('isEdit')) {
        todo.isEdit = true
      } else {
        this.$set(todo, 'isEdit', true)
      }
      // 想点击一触发，input框就获取焦点，但是editThisTodo这个函数必须执行完，页面才渲染出来input
      // 所以这个$nextTick的作用就是执行到这里的时候等页面渲染完再执行内部的回调函数
      this.$nextTick(function () {
        this.$refs.inputName.focus()
      })
    },
    saveEdit (todo, e) {
      if (!e.target.value.trim()) {
        alert('输入不能为空')
      }
      todo.isEdit = false
      let obj = { 'id': todo.id, 'name': e.target.value }
      pubsub.publish('updataTodo', obj)
    }
  },
}
</script>

<style scoped>
.todo {
  position: relative;
  width: 400px;
  height: 40px;
  border: 1px solid #ccc;
  line-height: 40px;
}
.todo:hover {
  background-color: #ccc;
}
.todo:hover .delBtn {
  display: block;
}
.todo:hover .editBtn {
  display: block;
}
span {
  padding-left: 5px;
}
.delBtn {
  position: absolute;
  top: 8px;
  right: 3px;
  height: 25px;
  background-color: red;
  color: #fff;
  line-height: 25px;
  border-radius: 5px;
  display: none;
  cursor: pointer;
}
.editBtn {
  position: absolute;
  top: 8px;
  right: 80px;
  height: 25px;
  background-color: skyblue;
  color: #fff;
  line-height: 25px;
  border-radius: 5px;
  display: none;
  cursor: pointer;
}
</style>
